/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClienteSocket.java
 *
 * Created on 27/10/2010, 06:53:48 AM
 */

package clientesocket;

import com.thoughtworks.xstream.XStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;


/**
 *
 * @author Francisco Gomez
 */
public class ClienteSocket extends javax.swing.JFrame {

    /** Creates new form ClienteSocket */
    public ClienteSocket() {
        initComponents();
        try {
            XStream xstream = new XStream();
            xstream.alias("Configuracion", Configuracion.class);
            BufferedReader in;
        try {
            in = new BufferedReader( new FileReader("C:/Config.xml"));
            String s, s2 = new String();
            try {
                while ((s = in.readLine()) != null)
                s2 += s + "\n";
                in.close();
            } catch (IOException ex) {
                Logger.getLogger(ClienteSocket.class.getName()).log(Level.SEVERE, null, ex);
            }
            Configuracion Config = (Configuracion)xstream.fromXML(s2);
            txtIPServer.setText(Config.getIp());
            txtPort.setText(Config.getPuerto());
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(rootPane, "Error durante la carga del archivo de configuración", "Error", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
            Logger.getLogger(ClienteSocket.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }catch(Exception e){
      //  System.out.print("Ocurrio un error en la carga de archivo de configuración");
        JOptionPane.showMessageDialog(rootPane, "Error durante la carga del archivo de configuración", "Error", JOptionPane.ERROR_MESSAGE);
    }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txtIPServer = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        txtPort = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        textNombre = new javax.swing.JTextField();
        textPass = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("IP Server:");

        txtPort.setEditable(false);

        jLabel3.setText("Port Server:");

        jButton2.setText("Enviar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Nombre:");

        jLabel5.setText("Password:");

        textPass.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textPassActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 25, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton2)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(textPass)
                        .addComponent(textNombre)
                        .addComponent(txtIPServer)
                        .addComponent(txtPort, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE)))
                .addContainerGap(67, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtIPServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(textNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(textPass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(32, 32, 32)
                .addComponent(jButton2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        
        try{    
        this.cliente = new Socket(this.txtIPServer.getText(), Integer.valueOf(this.txtPort.getText()));
        //PrintWriter salida = new PrintWriter(this.cliente.getOutputStream(), true);
        PrintWriter salida = new PrintWriter(this.cliente.getOutputStream(), true);
        BufferedReader entrada = new BufferedReader(new InputStreamReader(this.cliente.getInputStream()));
            
            System.out.println(textNombre.getText()+"."+textPass.getText());
            salida.println(textNombre.getText()+"."+textPass.getText());
//            this.jTextArea1.setText(this.jTextArea1.getText() + " resp:" + entrada.readLine());
//            System.out.print(entrada.readLine());
            if(entrada.readLine().equals("True")){
                JOptionPane.showMessageDialog(this, "Ya estas logeado", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            }else{
                JOptionPane.showMessageDialog(this, "Nombre o password incorrecto", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            }
            salida.close();
            entrada.close();
        this.cliente.close();

        } catch (Exception e) {
            mensajeError(e);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

private void textPassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textPassActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_textPassActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClienteSocket().setVisible(true);
            }
        });
    }

    private void mensajeError(Exception exception){
        
        String exceptionString = exception.getClass().getName().toString();
        StringTokenizer tokens = new StringTokenizer(exceptionString,".");
        boolean errorConexion = false;

        try{
            while (tokens.hasMoreTokens()){
                String exceptionStringConnect = tokens.nextToken();
                System.out.println(exceptionStringConnect);
                if (exceptionStringConnect.equalsIgnoreCase("ConnectException")){
                    JOptionPane.showMessageDialog(rootPane, "No existe conexión con el servidor", "Error", JOptionPane.ERROR_MESSAGE);
                    errorConexion = true;
                    break;
                }                    
            }
        } catch (Exception e){
        
        }
        
        if (!errorConexion)
            JOptionPane.showMessageDialog(rootPane, "Error durante la ejecución del programa", "Error", JOptionPane.ERROR_MESSAGE);
    }
    private Socket cliente;
    private boolean conectado = false;

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField textNombre;
    private javax.swing.JTextField textPass;
    private javax.swing.JTextField txtIPServer;
    private javax.swing.JTextField txtPort;
    // End of variables declaration//GEN-END:variables

}
